package com.ai.mall.controller.front;

import com.ai.mall.entity.UsersEntity;
import com.ai.mall.service.UsersService;
import com.ai.mall.utils.R;
import com.ai.mall.vo.req.UserRegisterRequest;
import com.fasterxml.jackson.core.type.TypeReference;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UsersService userService;

    /**
     * 用户注册接口
     *
     * @param userRegisterRequest 用户注册请求对象
     * @return 注册结果
     */
    @PostMapping("/register")
    @ApiOperation("用户注册接口")
    public R register(@ApiParam("用户注册请求对象") @RequestBody UserRegisterRequest userRegisterRequest) {
        // 调用 UserService 进行用户注册
        return userService.register(userRegisterRequest);
    }

    /**
     * 用户登录接口
     *
     * @param username 用户名
     * @param password 密码
     * @return 登录结果
     */
    @PostMapping("/login")
    public R login(@RequestParam String username, @RequestParam String password, HttpSession session) {
        // 调用UserService进行用户登录
        R result = userService.login(username, password);
        if (result.getCode() == 0) { // 假设R对象有一个isSuccess方法来判断登录是否成功
            // 获取用户信息并放入session
            UsersEntity user = result.getData("user", new TypeReference<UsersEntity>() {
            }); // 假设R对象有一个getData方法来获取用户信息
            session.setAttribute("user", user);
        }
        return result;
    }

    @GetMapping("/logout")
    @ApiOperation("用户登出接口")
    public R logout(
            @ApiParam("会话对象") HttpSession session) {
        // 实现登出逻辑
        session.removeAttribute("user");
        return R.ok();
    }

    /**
     * 获取用户信息接口
     *
     * @return 用户信息
     */
    @GetMapping("/getCurrentUserInfo")
    @ApiOperation("获取用户信息接口")
    public R getUserInfo(HttpSession session) {
        // 从session中获取用户信息
        UsersEntity userInfo = (UsersEntity) session.getAttribute("user");
        return R.ok().put("user", userInfo);
    }
}